include ApplicationHelper

class InvitationsController < ApplicationController
  include Devise::Controllers::InternalHelpers

  before_filter :authenticate_resource!, :only => [:new, :create]
  before_filter :require_no_authentication, :only => [:edit, :update]
  helper_method :after_sign_in_path_for

  # GET /resource/invitation/new
  def new
    #pragmatic-minds
    #si se viene de un contacto hay que setear el mail para la vista
    contact = Contact.find_by_id(session['contact_id'])
    if !contact.nil?
      @contact_mail = contact.email
    end

    authorize! :new, :invitations    
    build_resource

    #se elige la vista new en funcion de si se viene de un contacto o no
    if contact.nil?
      render_with_scope :new
    else
      render_with_scope :new_contact_user
    end
    #end pragmatic-minds
  end

  # POST /resource/invitation
  def create
    #pragmatic-minds
    contact = Contact.find_by_id(session['contact_id'])
    #previo a salvar verifico si ya existe un usuario con el mail elegido
    user_mail = params[resource_name]['email']
    user = User.find_by_email(user_mail)
    if !user.nil?
      flash[:error] = t('devise.invitations.msg_email_taken')
      if contact.nil?
        render_with_scope :new
      else
        render_with_scope :new_contact_user
      end
    else
      self.resource = resource_class.send_invitation(params[resource_name])
      if resource.errors.empty?

        #hay que setear por defecto al usuario el rol cliente
        user_mail = params[resource_name]['email']
        user = User.find_by_email(user_mail)
        user.roles_mask = 2
        user.save

        #si se crea el usuario desde un contacto hay que setearle al contacto el usuario
        contact = Contact.find_by_id(session['contact_id'])
        if !contact.nil?
          contact.user = user
          contact.save
        end

        set_flash_message :notice, :send_instructions

        #si se viene desde un contacto se vuelve al index de contact, sino al root app
        if contact.nil?
          redirect_to after_sign_in_path_for(resource_name)
        else
          redirect_to :controller => 'contacts', :action => 'index'
        end
      else
        if contact.nil?
          render_with_scope :new
        else
          render_with_scope :new_contact_user
        end        
      end
    end

    session['contact_id'] = nil
    #end pragmatic-minds
  end

  # GET /resource/invitation/accept?invitation_token=abcdef
  def edit
    self.resource = resource_class.new
    resource.invitation_token = params[:invitation_token]
    render_with_scope :edit
  end

  # PUT /resource/invitation
  def update
    self.resource = resource_class.accept_invitation!(params[resource_name])

    if resource.errors.empty?
      #pragmatic: iniciamos la session del usuario y lo enviamos a editar su contacto.
      flash_message :notice, t('devise.invitations.updated')      
      sign_in resource_name, resource #resource_name es :user y resource es el user
      user = resource
      contact = Contact.find_by_user_id(user.id)
      if !contact.nil?
        flash_message :notice, t('contacts.init_data')
        redirect_to edit_contact_path(contact)
      else
        set_flash_message :notice, :updated
        sign_in_and_redirect(resource_name, resource)
      end

    else
      render_with_scope :edit
    end
  end
end
